package com.shushan.exam;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.android.permission.FloatPermissionUtil;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.exam.bean.ExerciseResultBean;
import com.shushan.exam.bean.PaperBean;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.permission.OpenWindowActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.DateUtils;
import com.shushan.util.DialogUtil;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.GoodsDetailWebActivity;

import java.util.List;

/**
 * @ClassName: ExamScoreActivity
 * @Desciption: 考试成绩界面
 * @author: yichaohua
 * @date: 2018-01-08
 */
public class ExamScoreActivity extends BaseActivity implements View.OnClickListener, OnResultCollectListener
            ,Animation.AnimationListener{

    private static final String TAG = "ExamScoreActivity";

    private ImageView backImageView;
    private TextView timeTextView;
    private TextView chineseText,mathText,englisText;
    private TextView getTimeText,getToyText;
    private ImageView ivSurpriseImg;
    private Button btnWatchTopic,btnContinueExercise;
    private ImageView btnExamAgain;
    private ImageView ivExerciseContinue,ivUseNow,ivWatchWrongTopic,ivExchangeReward
            ,ivGetToyNow;
    private RelativeLayout rlGetToyLayout,rlFutureToyLayout;
    private RelativeLayout ustTimeLayout;
    private TextView tvWrongTopicNum;
    private TextView tvExerciseCountRest,tvFutureToyName;
    private TextView tvRewardStarNum;
    private RelativeLayout rlFirstToy;
    private ImageView ivGetSystemToyNow;
    private RelativeLayout rlWrongTopic;

    private int examTime;
    private int paperId = 0;
    private ExerciseResultBean exerciseResultBean;
    private PaperBean examPaperBean;
    private int awardType;
    private int examType = 1;//1、同步练习 2、智能练习 3、边学边练 4、重点练习 5、难点练习 6、易错练习 7、专项练习
    private RewardToyBean rewardToyBean;
    private RewardTimeBean rewardTimeBean;

    private boolean isFirstExercise = true;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int scoreSubjectNum = 0;//有得分的学科数

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScreenManager.getInstance().setStatusBar(true,this);
        setContentView(R.layout.exam_score_activity_new);

        examType = getIntent().getIntExtra("examType",0);
        examTime = getIntent().getIntExtra("examTime",0);
        paperId  = getIntent().getIntExtra("paperId",0);
        exerciseResultBean = (ExerciseResultBean) Session.getSession().get("exerciseResultBean");
        examPaperBean = (PaperBean) Session.getSession().get("examPaperBean");
        awardType = getIntent().getIntExtra("awardType",1);

        rewardTimeBean = (RewardTimeBean) Session.getSession().get("rewardTimeBean");
        rewardToyBean = (RewardToyBean) Session.getSession().get("rewardToyBean");

        initView();

        iniData();
    }

    private void initView() {
        ustTimeLayout = findViewById(R.id.exam_score_use_time_layout);
        getTimeText = findViewById(R.id.tv_get_time);
        getToyText = findViewById(R.id.tv_get_toy);
        chineseText = findViewById(R.id.tv_chinese_score);
        mathText = findViewById(R.id.tv_math_score);
        englisText = findViewById(R.id.tv_english_score);
        timeTextView = findViewById(R.id.exam_score_time_tv);
        backImageView = findViewById(R.id.top_left_back_img);
        backImageView.setOnClickListener(this);
        ivSurpriseImg = findViewById(R.id.iv_surprise_img);
        btnWatchTopic = findViewById(R.id.btn_watch_topic);
        btnWatchTopic.setOnClickListener(this);
        btnExamAgain = findViewById(R.id.btn_exam_again);
        btnExamAgain.setOnClickListener(this);
        ivExerciseContinue = findViewById(R.id.iv_exercise_continue);
        ivExerciseContinue.setOnClickListener(this);
        ivUseNow = findViewById(R.id.iv_use_now);
        ivUseNow.setOnClickListener(this);
        ivWatchWrongTopic = findViewById(R.id.iv_watch_wrong_topic);
        ivWatchWrongTopic.setOnClickListener(this);
        ivExchangeReward = findViewById(R.id.iv_exchange_reward);
        ivExchangeReward.setOnClickListener(this);
        ivGetToyNow = findViewById(R.id.iv_get_now);
        ivGetToyNow.setOnClickListener(this);
        rlGetToyLayout = findViewById(R.id.rl_get_toy_layout);
        rlFutureToyLayout = findViewById(R.id.rl_future_toy_layout);
        tvWrongTopicNum = findViewById(R.id.tv_wrong_topic_num);
        tvExerciseCountRest = findViewById(R.id.tv_exercise_count_rest);
        tvFutureToyName = findViewById(R.id.tv_future_toy_name);
        tvRewardStarNum = findViewById(R.id.tv_reward_star_num);
        btnContinueExercise = findViewById(R.id.btn_continue_exercise);
        btnContinueExercise.setOnClickListener(this);
        rlFirstToy = findViewById(R.id.rl_first_toy);
        ivGetSystemToyNow = findViewById(R.id.iv_get_system_toy_now);
        ivGetSystemToyNow.setOnClickListener(this);
        rlWrongTopic = findViewById(R.id.rl_wrong_topic);//错题栏
    }

    private void startSurpriseAnimation(Animation.AnimationListener listener){
        ivSurpriseImg.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this,R.anim.scale_normal_to_harf);
        ivSurpriseImg.setAnimation(animation);
        ivSurpriseImg.startAnimation(animation);
        animation.setAnimationListener(listener);
    }

    @Override
    public void onAnimationStart(Animation animation) {
        //do nothing
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        ivSurpriseImg.setVisibility(View.GONE);
        DialogUtil.showSurpriseDialog(this,this);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        //do nothing
    }

    private void iniData() {
        if(examPaperBean != null){
            if(ToolUtils.isListEmpty(examPaperBean.getChineseExerciseList())){
            }else{
                scoreSubjectNum++;
            }
            if(ToolUtils.isListEmpty(examPaperBean.getMathExerciseList())){
            }else{
                scoreSubjectNum++;
            }
            if(ToolUtils.isListEmpty(examPaperBean.getEnglishExerciseList())){
            }else{
                scoreSubjectNum++;
            }
        }

        if(exerciseResultBean.error_count <= 0){
            rlWrongTopic.setVisibility(View.GONE);
        }else {
            tvWrongTopicNum.setText(exerciseResultBean.error_count + "");
        }
        timeTextView.setText(StringTools.formatExamTime(examTime));
        if(exerciseResultBean != null){
            getTimeText.setText(exerciseResultBean.reward_time + "");

            if(TextUtils.isEmpty(exerciseResultBean.more_practice)){
                rlFutureToyLayout.setVisibility(View.GONE);
                if(!TextUtils.isEmpty(exerciseResultBean.toy_name)){
                    getToyText.setText(exerciseResultBean.toy_name);
                }else{
                    rlGetToyLayout.setVisibility(View.GONE);
                }
            }else{
                tvExerciseCountRest.setText(exerciseResultBean.more_practice);
                tvFutureToyName.setText(exerciseResultBean.toy_name);
                rlGetToyLayout.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(exerciseResultBean.first_toy)) {
                rlFirstToy.setVisibility(View.GONE);
            } else {
                startSurpriseAnimation(this);
            }

            tvRewardStarNum.setText(exerciseResultBean.stars_num+"");

            if(exerciseResultBean.reward_time <= 0){
                ustTimeLayout.setVisibility(View.GONE);
            }else {
                ustTimeLayout.setVisibility(View.VISIBLE);
            }

            //将该次练习得到的学贝数记入本地
            shuShanApplication.updateStars(exerciseResultBean.stars_num);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_get_system_toy_now:
            case R.id.btn_get_reward:
                //跳转奖品展示网页
                gotoToyWeb();
                DialogUtil.dismissDialog();
                break;
            case R.id.btn_watch_topic://查看习题
                Session.getSession().put("examPaperBean",examPaperBean);
                Intent intent = new Intent(this,ExamActivity.class);
                intent.putExtra("fromResultType",1);
                intent.putExtra("examTime",examTime);
                startActivityAllow(intent);
                break;
            case R.id.btn_exam_again://重考
                startRepeatExam();
                break;
            case R.id.iv_exercise_continue://继续练习
            case R.id.btn_continue_exercise://继续练习
                onBackAction();
                break;
            case R.id.iv_use_now://立即使用手机
                gotoGamesFloat();
                break;
            case R.id.iv_watch_wrong_topic://查看错题
                Session.getSession().put("examPaperBean",examPaperBean);
                Intent intent2 = new Intent(this,ExamActivity.class);
                intent2.putExtra("fromResultType",1);
                intent2.putExtra("isWatchWrongTopic",true);
                intent2.putExtra("examTime",examTime);
                startActivityAllow(intent2);
                break;
            case R.id.iv_exchange_reward://兑换奖品
                startActivity(MyStarActivity.class);
                break;
            case R.id.iv_get_now://立即领取
                startSurpriseAnimation(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        //do nothing
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        ivSurpriseImg.setVisibility(View.GONE);
                        DialogUtil.showSurpriseDialog(ExamScoreActivity.this,null,"领取奖品成功，奖品正飞奔而来！");
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        //do nothing
                    }
                });
                break;
            case R.id.top_left_back_img:
                onBackAction();
                break;
            default:
                break;
        }
    }

    private void gotoToyWeb() {
        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        UserBean currentUserBean = shuShanApplication.getUserBean();
        int childId = currentChildBean.id;
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.DIST_TOY_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "")
                .putValue("starsnum",currentChildBean.stars)
                .putValue("goodsid",0)
                .putValue("viptype",ToolUtils.getVipTypeForGoodsDetails(currentUserBean))
                ;

        Intent intent = new Intent(this, GoodsDetailWebActivity.class);
        intent.putExtra("title", "奖品详情");
        intent.putExtra("url", urlParse.toString());
        startActivityForResultAllow(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 200){
            showToast("领取成功");
            rlFirstToy.setVisibility(View.GONE);
        }else if(resultCode == 500){//玩具详情点击购买
            startActivity(OpenVipSpendActivity.class);
        }
    }

    private void startRepeatExam() {
        onBackAction();

        Session.getSession().put("rewardTimeBean",rewardTimeBean);
        Session.getSession().put("rewardToyBean",rewardToyBean);
        Session.getSession().put("examPaperBean",examPaperBean);

        Intent intent = new Intent(this, ExamActivity.class);
        intent.putExtra("awardType",awardType);
        intent.putExtra("fromResultType",0);
        intent.putExtra("paperId",paperId);
        startActivityAllow(intent);
    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType,final ExerciseBean exerciseBean) {
        int childId = shuShanApplication.getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", examType)
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST,new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if(exerciseBean.child_collect == 1){
                            exerciseBean.child_collect = 0;
                        }else {
                            exerciseBean.child_collect = 1;
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onResultCollect(ExerciseBean exerciseBean) {
        if(exerciseBean == null){
            return;
        }

        if(exerciseBean.child_collect == 0){
            doPostCollect(1,exerciseBean);
        }else {
            doPostCollect(2,exerciseBean);
        }
    }

    private void gotoGamesFloat() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl){
            showToast("请先进入家长模式开启管控");
            return;
        }

        boolean isAllowPlay = SharedPreferencesUtils.getBooleanDates(Constants.ALLOW_PLAY_SWITCH_SHAREPREFERS_KEY);
        if(!isAllowPlay){
            showToast("允许学习换取娱乐时间的开关已关闭");
            return;
        }

        if(SystemUtils.checkUsagePermission(this) && FloatPermissionUtil.checkPermission(this)){
            if(exerciseResultBean != null){
                setAllowBack(true);
                ActivityStackManager.getActivityStackManager().popAllActivity();

                GamesFloatWindow gamesFloatWindow = new GamesFloatWindow(shuShanApplication);
                gamesFloatWindow.setPaperId(exerciseResultBean.paper_id);
                GamesWindowManager.setGamesFloatWindow(gamesFloatWindow);
                GamesWindowManager.createGamesFloatWindow(shuShanApplication);

                //开启玩耍手机时间的闹钟
                setChildFree(exerciseResultBean.reward_time);
            }else {
                showToast("考试结果数据为空");
                return;
            }
        }else if(! FloatPermissionUtil.checkPermission(this)){
            showNoFloatDialog();
        } else if(!SystemUtils.checkUsagePermission(this)){
            showNoUsageDialog();
        }
    }

    private void setChildFree(int freeTime) {
        Log.i(TAG, "freeTime=" + freeTime + " setChildFree:" + DateUtils.getNowDate());

        if (freeTime > 0) {
            ToolUtils.setLockAlarm(this, freeTime);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    private void showNoFloatDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您的手机没有授予悬浮窗权限，请开启后再试")
                .setNegativeButton("暂不开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("现在去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenWindowActivity.class);
                    }
                })
                .create().show();
    }
}
